Page({
  data: {
    username: '',
    password: ''
  },

  onUsernameInput(e) {
    this.setData({
      username: e.detail.value
    });
  },

  onPasswordInput(e) {
    this.setData({
      password: e.detail.value
    });
  },

  async handleLogin() {
    const { username, password } = this.data;
    
    if (!username || !password) {
      wx.showToast({
        title: '请输入用户名和密码',
        icon: 'none'
      });
      return;
    }

    try {
      const cloud = getApp().globalData.cloud;
      if (!cloud) {
        throw new Error('云环境未初始化');
      }

      const db = cloud.database();
      const { data } = await db.collection('users')
        .where({
          username,
          password
        })
        .get();

      if (data.length === 0) {
        wx.showToast({
          title: '用户名或密码错误',
          icon: 'none'
        });
        return;
      }

      const userInfo = data[0];
      getApp().globalData.userInfo = userInfo;
      
      wx.showToast({
        title: '登录成功',
        icon: 'success'
      });

      if (userInfo.role === 'admin') {
        wx.redirectTo({
          url: '/pages/admin/index/index'
        });
      } else {
        wx.switchTab({
          url: '/pages/user/index/index'
        });
      }

    } catch (err) {
      console.error('登录失败：', err);
      wx.showToast({
        title: '登录失败，请重试',
        icon: 'error'
      });
    }
  },

  goToRegister() {
    wx.navigateTo({
      url: '/pages/register/register'
    });
  }
}); 